import { ipcRenderer } from 'electron'

const fsApi = {
  getFolder: (type?: 'Note' | 'Mind') => ipcRenderer.invoke('base-get-folder', type),
  setFolder: (type: 'Note' | 'Mind', folderPath: string) =>
    ipcRenderer.invoke('base-set-folder', type, folderPath),

  openFolder: () => ipcRenderer.invoke('fs-open-folder-dialog'),
  listMd: (folderPath: string) => ipcRenderer.invoke('fs-list-md', folderPath),
  readFile: (filePath: string) => ipcRenderer.invoke('fs-read-file', filePath),
  writeFile: (filePath: string, content: string) =>
    ipcRenderer.invoke('fs-write-file', filePath, content),
  renameFile: (filePath: string, newName: string) =>
    ipcRenderer.invoke('fs-rename-file', filePath, newName),
  deleteFile: (filePath: string) => ipcRenderer.invoke('fs-delete-file', filePath),

  // 渲染进程主动发起监听
  watch: (options: { folderPath?: string; filePath?: string }) =>
    ipcRenderer.invoke('fs-watch', options),
  stopWatch: () => ipcRenderer.invoke('fs-watch-stop'),

  // 当文件夹发生变化时，主进程通过 ipcRenderer 发送消息给渲染进程
  onFilesChanged: (cb: () => void) => {
    const handler = () => cb()
    ipcRenderer.on('fs-files-changed', handler)
    return () => ipcRenderer.removeListener('fs-files-changed', handler)
  },
  onFileChanged: (cb: (filePath: string) => void) => {
    const handler = (_: any, filePath: string) => cb(filePath)
    ipcRenderer.on('fs-file-changed', handler)
    return () => ipcRenderer.removeListener('fs-file-changed', handler)
  }
}

export default fsApi
